using ECommerce.Web.DesignByContract;
using ECommerce.Web.Models;
using ECommerce.Web.Services.ShoppingSessions;
using NHibernate;
using ECommerce.Web.NHibernate.Sessions;
using System;

namespace ECommerce.Web.Commands
{
    public interface IRemoveProductFromBasketCommand
    {
        void Handle(int productId);
    }

    public class RemoveProductFromBasketCommand : IRemoveProductFromBasketCommand
    {
        private readonly IShoppingSession shoppingSession;

        public RemoveProductFromBasketCommand(IShoppingSession shoppingSession)
        {
            this.shoppingSession = shoppingSession;
        }

        public void Handle(int productId)
        {
            Contract.Require(productId != default(int), "ProductId should not be default value.");

            Guid shopperToken = this.shoppingSession.GetShopperToken();

            ISession session = SessionSource.Current.GetSession();

            var shopper = session.FindById<IShopperWithBasket>(shopperToken);

            using (ITransaction transaction = session.BeginTransaction())
            {
                shopper.RemoveProductFromBasket(new Product() { Id = productId });

                transaction.Commit();
            }
        }
    }
}